package com.multi.framework.init;

import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.creator.DefaultDataSourceCreator;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DataSourceProperty;
import com.multi.source.domain.BkDataSourceInfo;
import com.multi.source.service.DataSourceInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.util.List;

/**
 * @Description 多租户数据库配置加载
 * @ClassName MultiDataSourceInit
 * @Author pzj
 * @Data 2024/11/20 10:17
 */
@Slf4j
@Component
public class MultiDataSourceInit implements ApplicationRunner {

    @Autowired
    private DataSourceInfoService dataSourceInfoService;
    @Autowired
    private DataSource dataSource;
    private DefaultDataSourceCreator dataSourceCreator;


    public MultiDataSourceInit(DataSource dataSource, DefaultDataSourceCreator dataSourceCreator) {
        this.dataSource = dataSource;
        this.dataSourceCreator = dataSourceCreator;
    }

    /**
     * 在springboot项目启动完成后加载数据库配置
     * 默认使用MYSQL8
     *
     * @param args
     */
    @Override
    public void run(ApplicationArguments args) {
        List<BkDataSourceInfo> entities = dataSourceInfoService.selectUsefulDataConfig();
        log.info("动态数据库配置开始!最终数据源总数量:{}", entities.size());
        // 当前动态数据源
        DynamicRoutingDataSource ds = (DynamicRoutingDataSource) dataSource;
        entities.forEach((item) -> {
            // 数据源参数配置
            DataSourceProperty dataSourceProperty = new DataSourceProperty();
            //固定使用mysql8
            String dbClassType = "com.mysql.cj.jdbc.Driver";
            String dbUrl = String.format("jdbc:mysql://%s:%s/%s?characterEncoding=utf8&useSSL=false", item.getDbIp(), item.getDbPort(), item.getDbName());
            //设置时区
            dbUrl=dbUrl.concat("&serverTimezone=GMT%2B8");
            dataSourceProperty.setPoolName(item.getTenantId().toString());
            dataSourceProperty.setUsername(item.getUsername());
            dataSourceProperty.setPassword(item.getPassword());
            dataSourceProperty.setUrl(dbUrl);
            dataSourceProperty.setDriverClassName(dbClassType);
            // 数据源全部懒加载,避免一次性声明过多连接
            dataSourceProperty.setLazy(true);
            // 生成数据源
            DataSource dataSource = dataSourceCreator.createDataSource(dataSourceProperty);
            // 添加到动态数据源中
            ds.addDataSource(item.getTenantId().toString(), dataSource);
            log.info("当前加载的数据源:{},加载完成!", item.getTenantId().toString());
        });
        log.info("动态数据库配置结束!总共加载{}个数据源!", ds.getDataSources().size());
    }
}

